﻿<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        Exception ex = HttpContext.Current.Server.GetLastError();
        if (ex.InnerException != null)
        {
            ex = ex.InnerException;
            
        }
        if (ex is HttpException)
        {
            if (((HttpException)ex).GetHttpCode() == 404)
            {
                Response.Redirect("~/PageNotFound.aspx");

            }
            else
            {
                Response.Redirect("~/ErrorPage.aspx");
            }
        }
        HttpContext.Current.Server.ClearError();
    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started
        int soluongtruycap = 0;
        //kiem tra file luu bien dem so nguoi truy cap co ton tai hay khong
        if (System.IO.File.Exists(Server.MapPath("~/DemSoNguoiOnline.txt")) == false)
        {
            soluongtruycap = 1;
        }
        else
        {
            // Đọc du liều từ file SoLuongTC.txt
            System.IO.StreamReader read = new System.IO.StreamReader(Server.MapPath("~/DemSoNguoiOnline.txt"));
            soluongtruycap = int.Parse(read.ReadLine());
            read.Close();
            //tang bien dem len 1
            soluongtruycap++;
        }
        //khoa website de tranh truong hop...bien dem tang lien tuc voi chi 1 nguoi truy cap roi
        Application.Lock();
        //gan bien application["soluongtruycap"]
        Application["soluongtruycap"] = soluongtruycap;
        //mo khoa website
        Application.UnLock();
        //luu lai du lieu de sau nay load len lai
        System.IO.StreamWriter write = new System.IO.StreamWriter(Server.MapPath("~/DemSoNguoiOnline.txt"));
        write.WriteLine(soluongtruycap);
        write.Close();
        if (Session["online"] == null)
        {
            Session["online"] = 1;
        }
        else
        {
            Session["online"] = int.Parse(Session["online"].ToString()) + 1;
        }

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        Session["online"] = int.Parse(Session["online"].ToString()) - 1;

    }
       
</script>
